﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repository
{
    public static class SafeConvert
    {
        public static int ToInt32(object value, int defaultValue = 0)
        {
            if (value == null || value == DBNull.Value)
                return defaultValue;

            if (value is int)
                return (int)value;

            if (int.TryParse(value.ToString(), out int result))
                return result;

            return defaultValue;
        }

        public static decimal ToDecimal(object value, decimal defaultValue = 0)
        {
            if (value == null || value == DBNull.Value)
                return defaultValue;

            if (value is decimal)
                return (decimal)value;

            if (decimal.TryParse(value.ToString(), out decimal result))
                return result;

            return defaultValue;
        }

        public static DateTime ToDateTime(object value, DateTime defaultValue = default)
        {
            if (value == null || value == DBNull.Value)
                return defaultValue == default ? DateTime.Now : defaultValue;

            if (value is DateTime)
                return (DateTime)value;

            if (DateTime.TryParse(value.ToString(), out DateTime result))
                return result;

            return defaultValue == default ? DateTime.Now : defaultValue;
        }

        public static DateTime? ToNullableDateTime(object value)
        {
            if (value == null || value == DBNull.Value)
                return null;

            if (value is DateTime)
                return (DateTime)value;

            if (DateTime.TryParse(value.ToString(), out DateTime result))
                return result;

            return null;
        }
    }
}
